<?php
namespace Orx\Etl;
/**
 * Data Extractor Object
 *
 * It represant the data extractor main object
 *
 * @author Xavier VILAIN
 * @package Orx\Etl
 * @license #license-orx-etl#
 *
 * @property int	$extractor	Extractor id
 * @property string	$language	Language
 * @property string	$label		Label
 * @property int	$type		Extractor Type (@see \Orx\Etl\Extractor\Type)
 * 
 */
class Extractor extends \Fox\Object\Versioned {

	/**
	 * Link to Translation
	 * @var string
	 */
	const LINK_I18N = 'i18n';

	/**
	 * Link to items
	 * @var string
	 */
	const LINK_ITEMS = 'items';

	/**
	 * Link to items
	 * @var string
	 */
	const LINK_SOURCE = 'source';
	
	/**
	 * Trigged when user initialize items using a file template
	 * @var string
	 */
	const CHANGE_IMPORT_TEMPLATE = 'import-template';
	
	/**
	 * 
	 * Result Grid Data
	 * @var array
	 */
	public $data = array();
	
	/**
	 * 
	 * Result Upload References 
	 * @var array
	 */
	public $references = array();
	
	/**
	 * 
	 * Result Upload Errors
	 * @var array
	 */
	public $errors = array();

	/**
	 * 
	 * Enter description here ...
	 * @var unknown_type
	 */
	private $_params = null;
	
	/**
	 * (non-PHPdoc)
	 * @see Fox.Object::afterSetFields($fields)
	 */
	protected function decodeParams() {
		$params = $this->params;
		if(!empty($params)) {
			$params = json_decode($params,true);
			if(is_array($params)) {
				foreach($params as $fieldname => $value) {
					$this->_params[$fieldname] = $value;
				}
			}
		}
	}
	
	/**
	 * Return Title
	 * @return string Element Title
	 */
	public function label() {
		return $this->i18nParse('label');
	}
	
	/**
	 * Process i18n to get the translated value if it exist,
	 * else the system will default to page value
	 * @param string $fieldName
	 * @return string
	 */
	public function i18nParse($fieldName) {
		$language = \Xview::instance()->language();
		$defaultLanguage = $this->language;
		if($language != $defaultLanguage) {
			$i18n = $this->findI18n($this->extractor.':'.$language);
			if($i18n->exists()) {
				return $i18n->$fieldName;
			}
			elseif(!empty($defaultLanguage)) {
				return null;
			}
		}
		return $this->$fieldName;
	}
	
	/**
	 * Build and return output format grid
	 * 
	 * @return \Fox\Grid
	 */
	public function outputGrid() {
		$grid = new \Fox\Grid('ouptput');
		foreach($this->items() as $field) {
			/* @var $field   Hive\Contact\Import\Format\Item */
			$iname = $field->reference.'_'.$field->sequence.'_'.$field->attribute;
			$idelm = $field->dataelement;
			$idelm = empty($idelm) ? $field->attribute : $idelm;
			if(empty($idelm)) {
				continue;
			}
			$fields[] = array($idelm,$iname);
		}
		if(!empty($fields)) {
			$grid->fieldcat($fields);
		}
		return $grid;
	}
	
	/**
	 * 
	 * Read uploaded file according to current format
	 * @param string $filename
	 */
	public function readFile($filename) {
		if(preg_match('/xls/',$filename)) {
			$result = Extractor\Source\Reader\SpreadSheet::read($filename, $this);
		} elseif(preg_match('/csv/',$filename)) {
			$result = Extractor\Source\Reader\Csv::read($filename, $this);
		} else {
			return null;
		}
		$this->data = $result['data'];
		$this->references = $result['references'];
		$this->errors = $result['errors'];
		return $this->data;
	}
	
	/**
	 * 
	 * Build Item collection using a file template
	 * @param string $filename
	 */
	public function buildTemplate($filename) {
		if(preg_match('/xls/',$filename)) {
			$result = Extractor\Source\Reader\SpreadSheet::readFirstRow($filename, $this);
		} elseif(preg_match('/csv/',$filename)) {
			$result = Extractor\Source\Reader\Csv::readFirstRow($filename, $this);
		} else {
			$result = array();
		}
		$position = 1;
		foreach($result as $fieldname) {
			$item = new Extractor\Item();
			$item->setFields(array('extractor' => $this->getId(),
									'position' => $position,
									'source_fieldname' => $fieldname,
									'mandatory' => false
							));
			$this->addToItems($item);
			$position++;
			unset($item);
		}
	}
	
	/**
	 * 
	 * Get Source Attribute Value
	 * @param string $name
	 * @return string
	 */
	public function attribute($name) {
		$this->decodeParams();
		if(isset($this->_params[$name])) {
			return $this->_params[$name];
		} else {
			return null;
		}
	}
}
\Fox\Dao::infos(Extractor::className(),new \Fox\Object\Info('etl_extractors', \Fox\Databases::DB_APP));

// Link to i18n elements
\Fox\Object\Links::add(\Fox\Dao::link(Extractor\I18n::className(),Extractor\I18n::LINK_EXTRACTOR)
->to(Extractor::className(), Extractor::LINK_I18N)
->on('extractor')
->cache(new \Fox\Dao\MemoryCacheZone(\Fox\Dao\MemoryCacheZone::PERIOD_FOREVER,Extractor::cacheDirectory()))
->versionFrom());

// Link to fields items
\Fox\Object\Links::add(\Fox\Dao::link(Extractor\Item::className(),Extractor\Item::LINK_EXTRACTOR)
->to(Extractor::className(), Extractor::LINK_ITEMS)
->on('extractor')
->orderBy('position')
->versionFrom());

// Link to fields items
\Fox\Object\Links::add(\Fox\Dao::link(Extractor::className(), Extractor::LINK_SOURCE)
->to(Extractor\Source::className(),Extractor\Source::LINK_EXTRACTOR)
->on('source')
->oneToOne());